﻿
var map;
var myLocation;
var infoWindow;
var mid=1;
function initialize() {	    
    var myOptions = {
        zoom: 12, 
        center: new google.maps.LatLng(14.058324, 108.277199), 
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    if(map==null)
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    GetCurrentLocation(map);
    	
    // Create the DIV to hold the control and call the HomeControl() constructor
    // passing in this DIV.
    var homeControlDiv = document.createElement('DIV');
    var homeControl = new HomeControl(homeControlDiv, map);

    homeControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
    
    google.maps.event.addListener(map, "rightclick",function(event){showContextMenu(event.latLng);});
	loadCatelogy();
}


$(document).ready(function() {
    //do jQuery stuff when DOM is ready
    //hideAllPanel();
	//showControl('pSearch');
});

function GetCurrentLocation(map)
{
	if (google.gears)
    {
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function (position) 
        {
            myLocation = new google.maps.LatLng(position.latitude, position.longitude);
            setCenter(myLocation);
        });
    }
	else if (navigator.geolocation) 
	{
		navigator.geolocation.getCurrentPosition(function (position) 
		{
			myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			setCenter(myLocation);
		}, function () {
            handleNoGeolocation(true);
        });
	}
	else{
		// Browser doesn't support Geolocation
        handleNoGeolocation(false);
	}
}

   
    
function handleNoGeolocation(errorFlag) {
    var content;
    if (errorFlag) {
        content = 'Error: The Geolocation service failed.';
    } else {
        content = 'Error: Your browser doesn\'t support geolocation.';
    }

    var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
    };

    var infowindow = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}

google.maps.event.addDomListener(window, 'load', initialize);
/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
*/

function HomeControl(controlDiv, map) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '2px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.title = 'Click to set the map to Home';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '4px';
    controlText.style.paddingRight = '4px';
    controlText.innerHTML = 'Home';
    controlUI.appendChild(controlText);

    // Setup the click event listeners: simply set the map to Chicago
    google.maps.event.addDomListener(controlUI, 'click', function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(myLocation);
            });
        }
    });

}

function setCenter(location)
{
	map.setCenter(location);			
}

function showMarket(idLocation, idCategory, name, address, comment, lat, lng)
{   
    var location = new google.maps.LatLng(lat, lng);
    setCenter(location);    
    var marker = createMarker(location);    
      
    google.maps.event.addListener(marker, 'click', function() {
    showInfo(marker, idLocation, idCategory, name, address, comment, lat, lng);
  });	
   
}

function showInfo(marker, idLocation, idCategory, name, address, comment, lat, lng)
{
	var infoWindow = createInfoWindow(idLocation, idCategory, name, address, comment, lat, lng);
	infoWindow.open(map,marker);
}


function createInfoWindow(idLocation, idCategory, name, address, comment, lat, lng)
{
	var infowindow = new google.maps.InfoWindow();
	var content = '<strong>' + name + '</strong></br>';
	content += '<div class=\"info\">';
	    content += '<div class=\"label\">địa chỉ:</div>';
	    content += '<div class=\"value\">' + address + '</div>';
	    content += '<div class=\"label\">mô tả:</div>'
	    content += '<div class=\"value\">' + comment + '</div>';
	    content += '<div class=\"vide\"></div>';
	    content += '<div class=\"link\"><a href=\'javascript:doDeleteLocation(' + idLocation + ')\'>xóa</a></div>';
	    content += '<div class=\"link\"><a href=\'javascript:editMenuSelected(' + idLocation +',' +idCategory+ ',\"' +name+'\",\"'+address+'\",\"'+comment+'\",'+lat+','+lng+')\'>sửa</a></div>';
	    content += '<div class=\"link\"><a href=\'javascript:shareLocation(' + idLocation + ')\'>chia sẻ</a></div>';
	content += '</div>';
	infowindow.setContent(content);
	return infowindow;
}

function doSearchLocation()
{
	var address = document.getElementById("txtSearch").value;
	var geocoderRequest = {'address':address};
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            showSearchResults(results[0].formatted_address, results[0].geometry.location.lat(), results[0].geometry.location.lng())
            var panel = document.getElementById("pSearchResults");
            var panelContent = "<strong>Các kết quả tìm được:</strong></br>";
		    for (var i in results) {
                panelContent += '<a href=\'javascript:showSearchResults(\"' + results[i].formatted_address + '\",' + results[i].geometry.location.lat() + ',' +results[i].geometry.location.lng()+ ')\'>' + results[i].formatted_address + '</a></br>';
            }
		    panel.innerHTML = panelContent;
		
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}


function linkDiaDiem_Click(name, location) {
}

function showSearchResults(name, lat, lng)
{
    var location = new google.maps.LatLng(lat, lng);
    map.setCenter(location);
    var marker = new google.maps.Marker({map: map,  position:location});
	
	var infowindow = new google.maps.InfoWindow();
	var content = '<strong>' + name + '</strong></br>';
	infowindow.setContent(content);
	infowindow.open(map, marker);		
	
	google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });
}

function selectPlace() {
    var a = $('#lbUserName').val();
    //alert(a);
    if(a=="" || a=="false")
    {
        alert("Bạn cần đăng nhập để thêm địa điểm");
        return;
    }
    showControl('pAddGuide');
    
    google.maps.event.clearListeners(map, 'click');
    google.maps.event.addListenerOnce(map, 'click', function (event) {
        addLocationSelectedLL(event.latLng);
    });
}

function createMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        draggable: true,
        animation: google.maps.Animation.DROP,
        map: map
    });
    marker.mid = mid++;    
    return marker;
}
